package com.qf.service.impl;

import com.qf.service.SearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author YDW
 * projectName:project2202_4
 * time:2022/6/24 14:18
 * description:
 */
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    RestHighLevelClient highLevelClient;
    @Override
    public List<Map> searchlist(String paras) throws IOException {
        Map<String,String> map=new HashMap<>();

        String[] Arr=paras.split(",");
        for (String s : Arr) {
            String[] split = s.split(":");
            map.put(split[0],split[1]);
        }
        String keyword = map.get("{\"keyword\"");
        String clientID = map.get("\"clientID\"");
        String mobile = map.get("\"mobile\"");
        String startTime = map.get("\"startTime\"");
        String endTime = map.get("\"endTime\"");
        String start = map.get("\"start\"");
        String rows = map.get("\"rows\"");
        String highLightPreTag = map.get("\"highLightPreTag\"");
        String highLightPostTag = map.get("\"highLightPostTag\"");
        String messageContent = map.get("\"messageContent\"");

        //1. SearchRequest
        SearchRequest request = new SearchRequest("sms_submit_log");

        //2. 指定查询条件（高亮）
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //2.1 指定查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(!StringUtils.isEmpty(keyword)){
            boolQuery.must().add(QueryBuilders.matchQuery("messageContent",keyword));
        }
        if(!StringUtils.isEmpty(clientID)){
            boolQuery.must().add(QueryBuilders.termQuery("clientID",clientID));
        }
        if(!StringUtils.isEmpty(mobile)&&!mobile.equalsIgnoreCase("\"\"")){
            boolQuery.must().add(QueryBuilders.wildcardQuery("mobile",mobile+"*"));
        }
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("sendTime");
        if(!StringUtils.isEmpty(startTime)&&!startTime.equalsIgnoreCase("null")){
            rangeQuery.gte(Long.parseLong(startTime));
        }
        if(!StringUtils.isEmpty(endTime)&&!endTime.equalsIgnoreCase("null")){
            rangeQuery.lte(Long.parseLong(endTime));
        }
        boolQuery.must().add(rangeQuery);
        if(!StringUtils.isEmpty(start)){
            builder.from(Integer.parseInt(start));
        }else {
            builder.from(0);
        }
        if(!StringUtils.isEmpty(rows)){
            builder.size(Integer.parseInt(rows));
        }else {
            builder.from(10);
        }

        builder.query(boolQuery);


        //2.2 指定高亮
        if(!StringUtils.isEmpty(messageContent)){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("messageContent")
                    .preTags(highLightPreTag)
                    .postTags(highLightPostTag);
            builder.highlighter(highlightBuilder);
        }
        request.source(builder);
        //3. 执行查询
        SearchResponse resp = highLevelClient.search(request, RequestOptions.DEFAULT);

        List<Map> list=new ArrayList<>();
        //4. 获取高亮数据，输出
        for (SearchHit hit : resp.getHits().getHits()) {
           Map<String,Object> source=hit.getSourceAsMap();
            list.add(source);
        }

    return list;

    }

    @Override
    public Long searchLogCount(String paras) throws IOException {
        Map<String,String> map=new HashMap<>();

        String[] Arr=paras.split(",");
        for (String s : Arr) {
            String[] split = s.split(":");
            map.put(split[0],split[1]);
        }

        String keyword = map.get("{\"keyword\"");
        String clientID = map.get("\"clientID\"");
        String mobile = map.get("\"mobile\"");
        String startTime = map.get("\"startTime\"");
        String endTime = map.get("\"endTime\"");
        String start = map.get("\"start\"");
        String rows = map.get("\"rows\"");
        String highLightPreTag = map.get("\"highLightPreTag\"");
        String highLightPostTag = map.get("\"highLightPostTag\"");
        String messageContent = map.get("\"messageContent\"");

        //1. SearchRequest
        SearchRequest request = new SearchRequest("sms_submit_log");

        //2. 指定查询条件（高亮）
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //2.1 指定查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(!StringUtils.isEmpty(keyword)){
            boolQuery.must().add(QueryBuilders.matchQuery("messageContent",keyword));
        }
        if(!StringUtils.isEmpty(clientID)){
            boolQuery.must().add(QueryBuilders.termQuery("clientID",clientID));
        }
        if(!StringUtils.isEmpty(mobile)&&!mobile.equalsIgnoreCase("\"\"")){
            boolQuery.must().add(QueryBuilders.wildcardQuery("mobile",mobile+"*"));
        }
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("sendTime");
        if(!StringUtils.isEmpty(startTime)&&!startTime.equalsIgnoreCase("null")){
            rangeQuery.gte(Long.parseLong(startTime));
        }
        if(!StringUtils.isEmpty(endTime)&&!endTime.equalsIgnoreCase("null")){
            rangeQuery.lte(Long.parseLong(endTime));
        }
        boolQuery.must().add(rangeQuery);
        if(!StringUtils.isEmpty(start)){
            builder.from(Integer.parseInt(start));
        }else {
            builder.from(0);
        }
        if(!StringUtils.isEmpty(rows)){
            builder.size(Integer.parseInt(rows));
        }else {
            builder.from(10);
        }

        builder.query(boolQuery);


        //2.2 指定高亮
        if(!StringUtils.isEmpty(messageContent)){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("messageContent")
                    .preTags(highLightPreTag)
                    .postTags(highLightPostTag);
            builder.highlighter(highlightBuilder);
        }
        request.source(builder);
        //3. 执行查询
        SearchResponse resp = highLevelClient.search(request, RequestOptions.DEFAULT);
        long count = resp.getHits().getTotalHits().value;
        return count;
    }
}
